package com.ren.controller;

import com.ren.entity.User;
import com.ren.service.UserService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/**
 * Created by Zero on 2017/5/31.
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private HttpServletResponse response;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private HttpSession session;

    private static final Logger LOGGER = Logger.getLogger(UserController.class);


    @RequestMapping(value="/add",method= RequestMethod.POST)
    public String addUser(@RequestBody User user){

        User selectUser=null;

        try {
            selectUser = userService.findUserByUserName(user.getUsername());
        }catch (NullPointerException e){
            e.printStackTrace();
        }

        if (selectUser == null){
            userService.addUser(user);
            return "true";
        } else {
            return "false";
        }
    }


    @RequestMapping(value="/login",method= RequestMethod.GET)
    public String login(String username,String password){

        User user = null;
        String result = null;
        try {
            user = userService.findByUserNameAndPwd(username, password);
        }catch (NullPointerException e){
            e.printStackTrace();
        }
        if (user == null){
            result = "false";
        }
        if (user != null){
            result = "true";
            try {
                Cookie cookie1 = new Cookie("USERACCOUNT", URLEncoder.encode(user.getUsername(), "UTF-8"));
                Cookie cookie2 = new Cookie("USERPWD",URLEncoder.encode(user.getPassword(),"UTF-8"));
                cookie1.setMaxAge(24*60*60);
                cookie2.setMaxAge(24*60*60);
                response.addCookie(cookie1);
                response.addCookie(cookie2);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            session.setAttribute("USER",user);
        }
        return result;
    }

}
